<script>
import { resetPassword, sendVerificationCode } from '@/api/user'
import { computed, ref } from 'vue'

export default {
  setup() {
    const form = ref(null)
    const accountTypeIndex = ref(0)
    const passwordStrength = ref(0)
    const countdown = ref(0)

    const formData = ref({
      account: '',
      verificationCode: '',
      newPassword: '',
      confirmPassword: '',
    })

    const strengthText = computed(() => {
      const texts = ['弱', '中', '强']
      return texts[passwordStrength.value - 1] || ''
    })

    const rules = {
      email: {
        rules: [
          { required: true, errorMessage: '请输入邮箱' },
          { format: 'email', errorMessage: '邮箱格式不正确' },
        ],
      },
      phone: {
        rules: [
          { required: true, errorMessage: '请输入手机号' },
          { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' },
        ],
      },
      verificationCode: {
        rules: [
          { required: true, errorMessage: '请输入验证码' },
          { pattern: /^\d{6}$/, errorMessage: '验证码格式不正确' },
        ],
      },
      newPassword: {
        rules: [
          { required: true, errorMessage: '请输入新密码' },
          { minLength: 6, errorMessage: '密码不能少于6位' },
        ],
      },
      confirmPassword: {
        rules: [
          { required: true, errorMessage: '请确认新密码' },
          {
            validateFunction: (rule, value, data) => {
              return value === data.newPassword
            },
            errorMessage: '两次输入的密码不一致',
          },
        ],
      },
    }

    const checkPasswordStrength = (password) => {
      let strength = 0
      if (password.length >= 6)
        strength++
      if (/[A-Z]/.test(password) && /[a-z]/.test(password))
        strength++
      if (/\d/.test(password) && /[^A-Z0-9]/i.test(password))
        strength++
      passwordStrength.value = strength
    }

    const onAccountTypeChange = (e) => {
      accountTypeIndex.value = e.currentIndex
      formData.value.account = ''
      formData.value.verificationCode = ''
    }

    const startCountdown = () => {
      countdown.value = 60
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)
    }

    const handleSendCode = async () => {
      try {
        const valid = await form.value.validate([accountTypeIndex.value === 0 ? 'email' : 'phone'])
        if (!valid)
          return

        await sendVerificationCode({
          type: accountTypeIndex.value === 0 ? 'email' : 'phone',
          account: formData.value.account,
        })

        uni.showToast({
          title: '验证码已发送',
          icon: 'success',
        })

        startCountdown()
      }
      catch (error) {
        console.error('发送验证码失败:', error)
      }
    }

    const handleResetPassword = async () => {
      try {
        const valid = await form.value.validate()
        if (!valid)
          return

        await resetPassword({
          type: accountTypeIndex.value === 0 ? 'email' : 'phone',
          account: formData.value.account,
          verificationCode: formData.value.verificationCode,
          newPassword: formData.value.newPassword,
        })

        uni.showToast({
          title: '密码重置成功',
          icon: 'success',
        })

        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/login/index',
          })
        }, 1500)
      }
      catch (error) {
        console.error('重置密码失败:', error)
      }
    }

    const goToLogin = () => {
      uni.navigateTo({
        url: '/pages/login/index',
      })
    }

    return {
      form,
      formData,
      rules,
      accountTypeIndex,
      passwordStrength,
      strengthText,
      countdown,
      onAccountTypeChange,
      checkPasswordStrength,
      handleSendCode,
      handleResetPassword,
      goToLogin,
    }
  },
}
</script>

<template>
  <view class="forgot-password-container">
    <view class="forgot-password-header">
      <text class="title">
        重置密码
      </text>
    </view>

    <view class="forgot-password-form">
      <uni-forms ref="form" :model-value="formData" :rules="rules">
        <uni-forms-item name="accountType">
          <uni-segmented-control
            :current="accountTypeIndex"
            :values="['邮箱验证', '手机验证']"
            @click-item="onAccountTypeChange"
          />
        </uni-forms-item>

        <uni-forms-item :name="accountTypeIndex === 0 ? 'email' : 'phone'">
          <uni-easyinput
            v-model="formData.account"
            :placeholder="accountTypeIndex === 0 ? '请输入注册邮箱' : '请输入注册手机号'"
          />
        </uni-forms-item>

        <uni-forms-item name="verificationCode">
          <view class="verification-code-input">
            <uni-easyinput
              v-model="formData.verificationCode"
              placeholder="请输入验证码"
              maxlength="6"
            />
            <button
              class="send-code-btn"
              :disabled="countdown > 0"
              @click="handleSendCode"
            >
              {{ countdown > 0 ? `${countdown}s后重试` : '发送验证码' }}
            </button>
          </view>
        </uni-forms-item>

        <uni-forms-item name="newPassword">
          <uni-easyinput
            v-model="formData.newPassword"
            type="password"
            placeholder="请输入新密码"
            @input="checkPasswordStrength"
          />
          <view class="password-strength">
            <text>密码强度：</text>
            <view class="strength-bars">
              <view
                v-for="(item, index) in 3"
                :key="index"
                class="strength-bar"
                :class="{ active: passwordStrength >= index + 1 }"
              />
            </view>
            <text class="strength-text">
              {{ strengthText }}
            </text>
          </view>
        </uni-forms-item>

        <uni-forms-item name="confirmPassword">
          <uni-easyinput
            v-model="formData.confirmPassword"
            type="password"
            placeholder="请确认新密码"
          />
        </uni-forms-item>
      </uni-forms>

      <button class="reset-btn" type="primary" @click="handleResetPassword">
        重置密码
      </button>

      <view class="back-to-login" @click="goToLogin">
        返回登录
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.forgot-password-container {
  padding: 40rpx;

  .forgot-password-header {
    text-align: center;
    margin-bottom: 60rpx;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
    }
  }

  .forgot-password-form {
    .verification-code-input {
      display: flex;
      gap: 20rpx;

      :deep(.uni-easyinput) {
        flex: 1;
      }

      .send-code-btn {
        width: 200rpx;
        height: 70rpx;
        line-height: 70rpx;
        font-size: 24rpx;
        background-color: #007AFF;
        color: #fff;
        border-radius: 35rpx;

        &[disabled] {
          background-color: #ccc;
        }
      }
    }

    .password-strength {
      display: flex;
      align-items: center;
      margin-top: 10rpx;
      font-size: 24rpx;
      color: #666;

      .strength-bars {
        display: flex;
        gap: 10rpx;
        margin: 0 10rpx;

        .strength-bar {
          width: 40rpx;
          height: 10rpx;
          background-color: #ddd;
          border-radius: 5rpx;

          &.active {
            &:nth-child(1) { background-color: #ff4d4f; }
            &:nth-child(2) { background-color: #faad14; }
            &:nth-child(3) { background-color: #52c41a; }
          }
        }
      }
    }

    .reset-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      margin: 40rpx 0;
      background-color: #007AFF;
      border-radius: 44rpx;
    }

    .back-to-login {
      text-align: center;
      font-size: 28rpx;
      color: #007AFF;
    }
  }
}
</style>
